import { Injectable } from "@angular/core";
import { CommonUtil } from "../util/common-util";

@Injectable({ providedIn: 'root' })
export class ConfigService {

	public v: ConfigValue;

	constructor() {
		this.v = this.load();
	}

	private load(): ConfigValue {
		let config: ConfigValue;
		let json = localStorage.getItem('config');
		if (json != null && json != '') {
			try {
				config = JSON.parse(json);
			} catch {
				config = new ConfigValue();
			}
		} else {
			config = new ConfigValue();
		}
		return this.checkConfig(config);
	}

	public save(): void {
		localStorage.setItem('config', JSON.stringify(this.v));
	}

	public checkConfig(config: ConfigValue): ConfigValue {
		if (config.theme != 'md' && config.theme != 'ios') {
			config.theme = ConfigService.get_MD_or_IOS();
		}
		if (config.dark_mode == null ||
			(config.dark_mode != 1 && config.dark_mode != 2 && config.dark_mode != 3)) {
			config.dark_mode = 1;
		}
		return CommonUtil.cloneDeep<ConfigValue>(config);
	}

	public static get_MD_or_IOS(): 'md' | 'ios' {
		return CommonUtil.isIOS() || CommonUtil.isSafari() ? 'ios' : 'md';
	}

	public static GET_THEME_BY_STATIC(): 'md' | 'ios' {
		let config: ConfigValue;
		let json = localStorage.getItem('config');
		if (json != null && json != '') {
			try {
				config = JSON.parse(json);
				return config.theme;
			} catch {
				return this.get_MD_or_IOS();
			}
		} else {
			return this.get_MD_or_IOS();
		}
	}

}

export class ConfigValue {
	public theme: 'md' | 'ios' = ConfigService.get_MD_or_IOS();
	public dark_mode: number = 1;
}
